﻿using System;
using Microsoft.SqlServer.Dts.Runtime;
using System.ComponentModel;

namespace PowerPivotUpdater
{
      [DtsTask
  (
   DisplayName = "Update PowerPivot",
   IconResource = "PowerPivotUpdater.Resources.TestIcon.ico",
   UITypeName = "PowerPivotUpdaterUI.UpdatePPTaskUI, PowerPivotUpdaterUI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=da7f8d5289b52764",
   TaskContact = "Update PowerPivot; SouthPublisher; PowerPivotUpdater.codeplex.com",
   RequiredProductLevel = DTSProductLevel.None
   )]

    public class UpdatePPTask: Task 
    {

          private string webSite = "";
          private string excelFileURL = "";
          private string connection = "";


        public override void InitializeTask(Connections connections, VariableDispenser variableDispenser, IDTSInfoEvents events, IDTSLogging log, EventInfos eventInfos, LogEntryInfos logEntryInfos, ObjectReferenceTracker refTracker)
        {
            base.InitializeTask(connections, variableDispenser, events, log, eventInfos, logEntryInfos, refTracker);
        }


          public override DTSExecResult Validate(Connections connections,
             VariableDispenser variableDispenser, IDTSComponentEvents events,
             IDTSLogging log)
          {

            DTSExecResult execResult = base.Validate(connections, variableDispenser, events, log);
            if (execResult != DTSExecResult.Success)
            {
                return execResult;
            }

            //validate Excel URL property
            try
            {
              if (this.webSite   == "")
              {
                events.FireError(0, "PowerPivot Updater", "The Web Site URL property must be configured.", "", 0);
                return DTSExecResult.Failure;
              }
              
              //validate Excel URL property
              if (this.excelFileURL  == "")
              {
                events.FireError(0, "PowerPivot Updater", "The Excel File URL property must be configured.", "", 0);
                return DTSExecResult.Failure;
              }
  
              // Validate Connection property
              if (this.connection   == "")
              {
                events.FireError(0, "PowerPivot Updater", "The Connection property must be configured.", "", 0);
                return DTSExecResult.Failure;
              }
              //validate workbook exists and connection exist within workbook

               bool isConnValid = false;
               string[] cons = ExcelServiceManager.GetBookConnections(this.WebSite, this.excelFileURL);
                foreach(string st in cons)
               {
                   if (st.ToLower() == this.connection.ToLower())
                   {
                        isConnValid = true;
                       break;
                   }
               }
               if (isConnValid )
                    return DTSExecResult.Success;
               else
               {
                      events.FireError(0, "Power Pivot Updater", "Connection not found in PowerPivot", "", 0);
                      return DTSExecResult.Failure;
               }
            }
            catch (System.Exception exception)
            {
              events.FireError(0, "Power Pivot Updater", exception.Message, "", 0);
              return DTSExecResult.Failure;
            }
          }

          public override DTSExecResult Execute(Connections cons,
                 VariableDispenser vars, IDTSComponentEvents events,
                 IDTSLogging log, Object txn)
          {
            try
            {
                if (this.webSite == "")
                {
                    events.FireWarning(0, "Power Pivot Uploader", "Web Site URL not specified", "", 0);
                    return DTSExecResult.Failure; 
                }
               if (this.excelFileURL == "")
                {
                    events.FireWarning(0, "Power Pivot Uploader", "Excel File URL not specified", "", 0);
                    return DTSExecResult.Failure; 
                }
               if (this.connection == "")
                {
                    events.FireWarning(0, "Power Pivot Uploader", "Connection not specified", "", 0);
                    return DTSExecResult.Failure; 
                }

               if (ExcelServiceManager.RefreshWorkbook(this.webSite, this.excelFileURL, this.connection))
               {
                   return DTSExecResult.Success;
               }
               else
               {
                   events.FireError(0, "Power Pivot Updater", "Connection not found in PowerPivot", "", 0);
                   return DTSExecResult.Failure;
               }
            }
            catch (System.Exception exception)
            {
                //   Capture the exception and post an error.
                events.FireError(0, "Power Pivot Updater", exception.Message, "", 0);
                return DTSExecResult.Failure;
            }
        }

      [Category("General"), Description("Excel File URL")]
      public string ExcelFileURL
      {
        get
        {
          return this.excelFileURL ;
        }
        set
        {
          this.excelFileURL  = value;
        }
      }

      [Category("General"), Description("Sharepoint Site"), TypeConverter(typeof(SiteSelector))]    
      public string WebSite
      {
        get
        {
          return this.webSite;
        }
        set
        {
          this.webSite  = value;
        }
      }

      [Category("General"), Description("Connection"), TypeConverter(typeof(ConnectionSelector))]
      public string Connection
      {
          get
          {
              return this.connection;
          }
          set
          {
              this.connection = value;
          }
      }


    }
}
